define([], function () {
    function UploadAdapter(elem, done) {
        return new (function (elem, done) {
            let that = this;
            /*! 初始化变量 */
            this.option = {elem: $(elem), exts: [], mimes: []};
            this.option.hide = this.option.elem.data('hide') ? 1 : 0;
            this.option.mult =  0;
            this.option.quality = parseFloat(this.option.elem.data('quality') || '1.0');
            this.option.maxWidth = parseInt(this.option.elem.data('max-width') || '0');
            this.option.maxHeight = parseInt(this.option.elem.data('max-height') || '0');
            this.option.cutWidth = parseInt(this.option.elem.data('cut-width') || '0');
            this.option.cutHeight = parseInt(this.option.elem.data('cut-height') || '0');
            this.option.acceptMime = this.option.elem.data('accept-mime');
            this.option.fileType = this.option.elem.data('file-type');
            this.adapter = new Adapter(this.option, layui.upload.render(
                {
                    auto: false,
                    elem: elem,
                    accept: 'file',
                    multiple: this.option.mult, exts: this.option.exts.join('|'), acceptMime: this.option.acceptMime, choose: function (obj) {
                        obj.items = [], obj.files = obj.pushFile();
                        layui.each(obj.files, function (idx, file) {
                            obj.items.push(file);
                            file.path = that.option.path;
                            file.quality = that.option.quality;
                            file.maxWidth = that.option.maxWidth;
                            file.maxHeight = that.option.maxHeight;
                            file.cutWidth = that.option.cutWidth;
                            file.cutHeight = that.option.cutHeight;
                            file.mime =that.option.acceptMime;
                            file.fileType = that.option.fileType;
                        });
                        that.adapter.event('upload.choose', obj.items);
                        that.adapter.event("upload.process")
                        that.adapter.upload(obj.items, done);
                        layui.each(obj.files, function (idx) {
                            delete obj.files[idx];
                        });

                    }
                }));
        })(elem, done)
    }
    // 创建对象
    UploadAdapter.adapter = window.AdminUploadAdapter = Adapter;
    // 上传文件
    function Adapter(option, uploader) {
        this.uploader = uploader, this.config = function (option) {
            return (this.option = Object.assign({}, this.option || {}, option || {})), this;
        }, this.init = function (option) {
            this.uploader && this.uploader.config.elem.next().val('');
            this.files = {}, this.count = {total: 0, error: 0, success: 0};
            return this.config(option);
        }, this.init(option);
    }
    // 文件推送
    Adapter.prototype.upload = function (files, done) {
        let that = this.init();
        layui.each(files, function (index, file) {
            that.count.total++, file.index = index, that.files[index] = file;
            if (!that.option.hide && !file.notify) {
                file.notify = new NotifyExtend(file);
            }
            // 图片限宽限高压缩
            let isGif = /^image\/gif/.test(file.type);
            if (!isGif && /^image\//.test(file.type) && (file.maxWidth + file.maxHeight + file.cutWidth + file.cutHeight > 0 || file.quality !== 1)) {
                require(['compressor'], function (Compressor) {
                    let options = {quality: file.quality, resize: 'cover'};
                    if (file.cutWidth) options.width = file.cutWidth;
                    if (file.cutHeight) options.height = file.cutHeight;
                    if (file.maxWidth) options.maxWidth = file.maxWidth;
                    if (file.maxHeight) options.maxHeight = file.maxHeight;
                    new Compressor(file, Object.assign(options, {
                        success(blob) {
                            blob.index = file.index, blob.notify = file.notify, blob.path = file.path,blob.fileType=file.fileType,files[index] = blob;
                            that.request(files[index], done);
                        }, error: function () {
                            that.event('upload.error', {file: file}, file, '图片压缩失败');
                        }
                    }));
                });
            } else {
                that.request(file, done);
            }
        });
    };

    // 文件上传
    Adapter.prototype.request = function (file, done) {
        let uuid =this.uuid();
        this.ajax(1,file,uuid,done);
    }
    //uuid 生成
    Adapter.prototype.uuid = function () {
        var d = new Date().getTime();
        if (window.performance && typeof window.performance.now === "function") {
            d += performance.now();
        }
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;    // d是随机种子
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }
    Adapter.prototype.ajax=function (number,file,uuid,done) {
        var that = this;
        let LENGTH = 1024*100; //每片文件大小
        let size = file.size
        let total_num = Math.ceil(size / LENGTH);
        let blob = file.slice((number - 1) * LENGTH, number * LENGTH)
        form = new FormData();
        form.append("current_num",number);
        form.append("total_num",total_num);
        form.append("uuid",uuid);
        form.append('size',size);
        form.append('file', blob, file.name);
        form.append('file_type', file.fileType);
        jQuery.ajax({
            url:UPLOAD_URL,
            data:form,
            type:"post",
            contentType: false,
            error:function () {
                that.event('upload.error', {file: file}, file, '上传接口异常！');
            },
            processData: false,
            dataType:"json",
            success:function (res){
                percent = (number/total_num).toFixed(2)*100
                that.progress(percent, file)
                if (res.code==0) {
                    if (res.state==1) {
                        that.done(res, file, file, done,res.msg);
                    } else {
                        number++;
                        that.ajax(number,file,uuid,done)
                    }
                } else {
                    that.event('upload.error', {file: file}, file, res.msg);
                }
            },
        })
    }
    // 上传结果
    Adapter.prototype.done = function (ret, idx, file, done,message) {
        if (ret.code > 1) {
            return $.msg.tips(ret.msg || '文件上传失败！')
        }
        if (typeof done === 'function') {
            done.call(this.option.elem, ret.url, this.files['uuid']);
        } else if (this.option.mult < 1 && this.option.elem.data('input')) {
            $(this.option.elem.data('input')).val(ret.url).trigger('change', file);
        }
        this.event('upload.done', {file: file, data: ret}, file, message);
    };


    // 上传进度
    Adapter.prototype.progress = function (number, file) {
        if (file.notify) file.notify.setProgress(number);
    };
    /*! 触发事件过程 */
    Adapter.prototype.event = function (name, data, file, message) {
        if (name === 'upload.error') {
            this.count.error++, file.xstate = -1, file.xstats = message;
            if (file.notify) file.notify.setError(message);
        } else if (name === 'upload.done') {
            this.count.success++, file.xstate = 1, file.xstats = message;
            if (file.notify) file.notify.setSuccess(message)
        } else if(name==="upload.process") {
            layui.element.progress('lock_progress', '0%');
        }
        if (this.option.elem) {
            this.option.elem.triggerHandler(name, data);
            if (this.option.input) this.option.input.triggerHandler(name, data);
        }
        return this;
    };
    return UploadAdapter;

    function NotifyExtend(file) {
        var html =`<div class="uploadLoadingDiv""> <div class="layui-progress" lay-showpercent="true" lay-filter="lock_progress" style="margin: 20px 10px;">
        <div class="layui-progress-bar layui-bg-blue" lay-percent="0%"><span class="layui-progress-text"></span></div>
        </div</div>`;
           var obj = $(html);
        obj.index =layui.layer.open({
            type: 1,
            title: '上传进度',
            closeBtn: 1,
            area: ['300px', '100px'],
            shadeClose: false,
            content: obj.html(),
            offset: '200px'
        });
        layui.element.progress('lock_progress', '0%');
        obj.setProgress = function (percent) {
            layui.element.progress('lock_progress', percent+ '%');

            return  obj;
        },  obj.setError = function (message) {
            obj.find('.res').html(message || '文件上传失败！');
            layui.element.progress('lock_progress', '0%');
            return obj.close();
        },  obj.setSuccess = function (message) {
            layui.element.progress('lock_progress', 100+ '%');
            obj.append("<span>"+message+"</span>");
            return  obj.close();
        },  obj.close = function (timeout) {
            return setTimeout(function () {
            layui.layer.close(obj.index)
            }, timeout || 2000),obj;
        };
        return obj;
    }
});